package com.vichat.workflow.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.vichat.workflow.entity.*;
import com.vichat.workflow.service.IWorkflowServcie;
import com.vichat.workflow.service.WorkflowConstant;
import com.vichat.workflow.vo.WfNodePropsVO;
import com.vichat.workflow.vo.WorkflowUser;
import com.vichat.common.cache.RedisHelper;
import com.vichat.common.util.NumberUtils;
import com.vichat.common.util.StringUtil;
import com.vichat.common.vo.Json;
import com.vichat.common.vo.PageFilter;
import com.vichat.res.service.IResService;
import com.vichat.user.entity.SecRole;
import com.vichat.user.entity.UserBasic;
import com.vichat.user.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by wangluyin on 2018/6/14.
 */
@Controller
@RequestMapping("/wfApi")
public class WorkflowApiController extends WorkflowController {
    protected static final Logger logger = LoggerFactory.getLogger(WorkflowController.class);
    @Autowired
    HttpServletRequest request;
    @Autowired
    HttpServletResponse response;
    @Autowired
    private IWorkflowServcie workflowServcie;

    @Autowired
    private IUserService userService;

    @Autowired
    protected IResService resService;

    @RequestMapping("/getMobileStartNodeProps")
    @ResponseBody
    public Json getMobileStartNodeProps(long uid, String passwd, String flowCode) {
        Json json = new Json();
        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }
            WfNodePropsVO nodeProps = new WfNodePropsVO();
            Wf wf = workflowServcie.getWorkflowByFlowCode(flowCode);
            if (wf == null) {
                throw new Exception("未找到工作流模板");
            }
            nodeProps.setWf(wf);
            WfNode node = workflowServcie.getWfStartNode(wf.getFlowId());
            if (node == null) {
                throw new Exception("工作流节点数据异常");
            }
            nodeProps.setWfNode(node);
            List<WfNodeAttrFieldset> fieldsets = workflowServcie.getAttrFieldsetByNodeId(node.getNodeId(), node.getFlowId());
            for (WfNodeAttrFieldset fieldset : fieldsets) {
                List<WfNodeAttr> attrs = workflowServcie.getAttrsByFieldsetId(node.getNodeId(), fieldset.getFieldsetId());
                List<JSON> attrsJson = getAttrJson(attrs);
                fieldset.setAttrs(attrsJson);
            }
            nodeProps.setAttrFieldsets(fieldsets);
            json.setObj(nodeProps);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    @RequestMapping("/startMobileFlow")
    @ResponseBody
    public Json startFlow(long uid, String passwd, @RequestBody Map<String, Object> models) {
        Json json = new Json();

        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }
            if (!models.containsKey("flowId")) {
                throw new Exception("传入参数错误:flowId为空");
            }
            if (!models.containsKey("nodeId")) {
                throw new Exception("传入参数错误:nodeId为空");
            }

            int flowId = NumberUtils.toInt(models.get("flowId").toString());
            int nodeId = NumberUtils.toInt(models.get("nodeId").toString());

            if (NumberUtils.isNullOrZero(flowId)) {
                throw new Exception("传入参数错误:flowId为空");
            }
            if (NumberUtils.isNullOrZero(nodeId)) {
                throw new Exception("传入参数错误:nodeId为空");
            }

            Wf wf = workflowServcie.getWorkflowById(flowId);
            if (wf == null) {
                throw new Exception("未找到工作流模板");
            }

            WfNode node = workflowServcie.getWfStartNode(flowId);
            if (node == null) {
                throw new Exception("工作流节点数据异常");
            }
            WorkflowUser workflowUser = toWorkflowUser(user);

            InsWf insWf = workflowServcie.startFlow(wf, node, models, workflowUser);

            json.setObj(insWf);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    @RequestMapping("/commitMobileFlow")
    @ResponseBody
    public Json commitMobileFlow(long uid, String passwd, @RequestBody Map<String, Object> models) {
        Json json = new Json();

        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }

            if (!models.containsKey("insNodeId")) {
                throw new Exception("传入参数错误:insNodeId为空");
            }
            int insNodeId = (Integer) models.get("insNodeId");
            if (NumberUtils.isNullOrZero(insNodeId)) {
                throw new Exception("传入参数错误:insNodeId为空");
            }

            WorkflowUser workflowUser = toWorkflowUser(user);
            ;
            InsWf insWf = workflowServcie.commitFlow(insNodeId, models, workflowUser);

            json.setObj(insWf);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    @RequestMapping("/saveMobileFlow")
    @ResponseBody
    public Json saveMobileFlow(long uid, String passwd, @RequestBody Map<String, Object> models) {
        Json json = new Json();

        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }

            if (!models.containsKey("insNodeId")) {
                throw new Exception("传入参数错误:insNodeId为空");
            }
            int insNodeId = (Integer) models.get("insNodeId");
            if (NumberUtils.isNullOrZero(insNodeId)) {
                throw new Exception("传入参数错误:insNodeId为空");
            }

            WorkflowUser workflowUser = toWorkflowUser(user);
            InsWf insWf = workflowServcie.saveFlow(insNodeId, models, workflowUser);

            json.setObj(insWf);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    @RequestMapping("/getMobileTodoInsFlows")
    @ResponseBody
    public Json getMobileTodoInsFlows(long uid, String passwd, String startTime, String endTime, String deadTime, Integer flowState, Integer nodeState, PageFilter pf) {
        Json json = new Json();
        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }

            String roles = StringUtils.join(getRolesByUid(user.getUid()), ",");

            List<InsWfNode> insWfNodes = workflowServcie.getInsFlowNodesByPage(0l, null, user.getPartyId(), 0L, user.getUid(), user.getOrgId(), roles, user.getOrgCode(), startTime, endTime, deadTime, flowState, nodeState, pf);
            if (insWfNodes != null && !insWfNodes.isEmpty()) {
                if (NumberUtils.isNotNullOrZero(nodeState) && nodeState.longValue() == WorkflowConstant.FLOW_STATE_TODO) {
                    for (InsWfNode node : insWfNodes) {
                        StringBuilder sb = new StringBuilder();
                        if (NumberUtils.isNotNullOrZero(node.getUid())) {
                            String excuteName = RedisHelper.getUname(node.getUid());
                            sb.append(excuteName).append(",");
                        }

                        List<UserBasic> todoUserBasics = userService.queryUserByFuncDesc(new String[]{"wf_approvel"}, node.getOrgId());
                        for (UserBasic todoUserBasic : todoUserBasics) {
                            sb.append(todoUserBasic.getUserName()).append(",");
                        }
                        node.setTodoUsers(sb.toString());
                    }
                }

                json.setObj(insWfNodes);
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    protected List<Long> getRolesByUid(long uid) {
        List<SecRole> roleList = userService.querySecRoleByUid(uid);
        List<Long> roles = new ArrayList();
        for (SecRole role : roleList) {
            roles.add(role.getRoid());
        }
        return roles;
    }

    /**
     * 获取当前用户创建的任务流程数据
     *
     * @param uid
     * @param passwd
     * @param pf
     * @return
     */
    @RequestMapping("/getMobileMyCrtInsFlows")
    @ResponseBody
    public Json getMobileMyCrtInsFlows(long uid, String passwd, PageFilter pf) {
        Json json = new Json();
        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }
            List<InsWf> insFlows = workflowServcie.getInsFlows(0l, null, user.getUid(),null, null, null, WorkflowConstant.FLOW_STATE_DONE,null, null,pf);
            json.setObj(insFlows);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     * 查询用户相关已经结束任务流程
     *
     * @param pf
     * @return
     */
    @RequestMapping("/getMobileFinishInsFlows")
    @ResponseBody
    public Json getMobileFinishInsFlows(long uid, String passwd, PageFilter pf) {
        Json json = new Json();
        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }
            List<InsWf> insFlows = workflowServcie.getInsFlows(0l, null,null, user.getUid(), null, null, WorkflowConstant.FLOW_STATE_DONE,null,null, pf);
            json.setObj(insFlows);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    /**
     * 查询用户已经处理的任务流程(流程完成or未完成)
     *
     * @param pf
     * @return
     */
    @RequestMapping("/getMobileDoneInsFlows")
    @ResponseBody
    public Json getMobileDoneInsFlows(long uid, String passwd, PageFilter pf) {
        Json json = new Json();
        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }
            List<InsWf> insFlows = workflowServcie.getInsFlows(0l, null,null, user.getUid(), null, null, null,WorkflowConstant.FLOW_STATE_DONE, null,pf);
            json.setObj(insFlows);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }


    @RequestMapping("/getMobileFlowProps")
    @ResponseBody
    public Json getMobileFlowProps(long uid, String passwd,long insFlowId) {
        Json json = new Json();
        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }
            InsWf insWf = workflowServcie.getInsFlowById(insFlowId);
            List<WfNodeAttrFieldset> fieldsets = workflowServcie.getAttrFieldsetByNodeId(-1L, insWf.getFlowId());
            List<JSON> attrsJson = new ArrayList<>();
            for (WfNodeAttrFieldset fieldset : fieldsets) {
                List<WfNodeAttr> attrs = workflowServcie.getAttrsByFieldsetId(-1, fieldset.getFieldsetId());
                attrsJson.addAll(getAttrJsonWithValue(attrs, insFlowId, -1));
                fieldset.setAttrs(attrsJson);
            }

            json.setObj(attrsJson);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }



    @RequestMapping("/getMobileInsNodesByInsFlowId")
    @ResponseBody
    public Json getMobileInsNodesByInsFlowId(long uid, String passwd, long insFlowId) {
        Json json = new Json();
        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }
            List<InsWfNode> insWfNodes = workflowServcie.getInsNodesByInsFlowId(insFlowId);
            if (insWfNodes != null) {
                for (InsWfNode node : insWfNodes) {
                    if (node.getNodeState() == WorkflowConstant.FLOW_STATE_TODO) {
                        StringBuilder sb = new StringBuilder();
                        if (NumberUtils.isNotNullOrZero(node.getUid())) {
                            String excuteName = RedisHelper.getUname(node.getUid());
                            sb.append(excuteName).append(",");
                        }
//                        if (NumberUtils.isNotNullOrZero(node.getRoleId()) && NumberUtils.isNotNullOrZero(node.getOrgId())) {
//                            List<UserBasic> todoUserBasics = resService.getUserBasicsByRole(node.getRoleId(), node.getOrgId(), null);
//                            for (UserBasic todoUserBasic : todoUserBasics) {
//                                if(sb.toString().indexOf(todoUserBasic.getUserName()) == -1) {
//                                    sb.append(todoUserBasic.getUserName()).append(",");
//                                }
//                            }
//                        }
//                        if (NumberUtils.isNotNullOrZero(node.getRoleId()) && StringUtils.isNotBlank(node.getOrgCode())) {
//                            List<UserBasic> todoUserBasics = resService.getUserBasicsByRole(node.getRoleId(), null, node.getOrgCode());
//                            for (UserBasic todoUserBasic : todoUserBasics) {
//                                if(sb.toString().indexOf(todoUserBasic.getUserName()) == -1) {
//                                    sb.append(todoUserBasic.getUserName()).append(",");
//                                }
//                            }
//                        }
                        node.setTodoUsers(sb.toString());
                    }
                }
                json.setObj(insWfNodes);
            }
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }

    @RequestMapping("/getMobileNodePropsByNodeId")
    @ResponseBody
    public Json getNodePropsByNodeId(long uid, String passwd, long insNodeId) {
        Json json = new Json();
        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }
            InsWfNode insWfNode = workflowServcie.getInsWfNodeById(insNodeId);
            WfNodePropsVO nodeProps = new WfNodePropsVO();
            WfNode node = workflowServcie.getWfNodeByNodeId(insWfNode.getNodeId());
            nodeProps.setWfNode(node);
            if (node == null) {
                throw new Exception("工作流节点数据异常");
            }
            Wf wf = workflowServcie.getWorkflowById(node.getFlowId());
            if (wf == null) {
                throw new Exception("工作流节点数据异常");
            }
            nodeProps.setWf(wf);
            List<WfNodeAttrFieldset> fieldsets = workflowServcie.getAttrFieldsetByNodeId(node.getNodeId(), node.getFlowId());
            for (WfNodeAttrFieldset fieldset : fieldsets) {
                List<WfNodeAttr> attrs = workflowServcie.getAttrsByFieldsetId(node.getNodeId(), fieldset.getFieldsetId());
                List<JSON> attrsJson = getAttrJsonWithValue(attrs, insWfNode.getInsFlowId(), insNodeId);
                fieldset.setAttrs(attrsJson);
            }
            nodeProps.setAttrFieldsets(fieldsets);

            if (StringUtils.isNotBlank(node.getNodeExp())) {
                JSONObject nodeJson = JSON.parseObject(node.getNodeExp());
                String isPrint = nodeJson.getString("isPrint");
                String isBack = nodeJson.getString("isBack");
                nodeProps.setIsBack(StringUtil.stringToBoolean(isBack));
                nodeProps.setIsPrint(StringUtil.stringToBoolean(isPrint));
            }

            json.setObj(nodeProps);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }


    @RequestMapping("/saveMobileTaskChannelId")
    @ResponseBody
    public Json saveMobileTaskChannelId(long uid, String passwd, long insFlowId,long channelId) {
        Json json = new Json();
        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }

            InsWf  insWf =  workflowServcie.updateInsWfAttr(insFlowId,String.valueOf(channelId));

            json.setObj(insWf);
            json.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }


    @RequestMapping("/getMobileInsWfById")
    @ResponseBody
    public Json getMobileInsWfById(long uid, String passwd, long insFlowId) {
        Json json = new Json();
        try {
            UserBasic user = userService.getUserBasicByUid(uid);
            if (!StringUtils.equals(passwd, user.getPassword())) {
                throw new Exception("接口参数UID和密码不对应,请重新登录");
            }

            InsWf  insWf =  workflowServcie.getInsFlowById(insFlowId);
            if(insWf.getPartyId().longValue() == user.getPartyId().longValue()) {
                json.setObj(insWf);
                json.setSuccess(true);
            }else{
                json.setMsg("数据异常，未找到任务数据");
                json.setSuccess(false);
            }

        } catch (Exception e) {
            e.printStackTrace();
            json.setMsg(e.getMessage());
        }
        return json;
    }


}